import React, { useState } from 'react';
import { InfiniteScroll } from 'antd-mobile';
import KnowledgeCard from '@/views/Home/components/KnowledgeCard/KnowledgeCard';
import type { Knowledge, KnowledgeParams, KnowledgeType } from '@/type/HomeTyoe';
import { fetchKnowledgeList } from '@/store/modules/homeStore';
import { SpinLoading, Toast } from 'antd-mobile';
import { useEnhanceDispatch } from '@/hooks';
import './KnowledgeList.scss';

interface KnowledgeListProps {
  type: KnowledgeType;
}

const KnowledgeList: React.FunctionComponent<KnowledgeListProps> = ({ type }) => {
  const enhanceDispatch = useEnhanceDispatch();
  // 获取文章列表的参数
  const [knowledgeParams, setKnowledgeParams] = useState<KnowledgeParams>({ current: 1, pageSize: 10, type });
  // loading效果
  const [loading, setLoading] = useState<boolean>(false);
  // 是否还有更多内容
  const [hasMore, setHasMore] = useState(true);
  // 文章列表
  const [knowledgeList, setknowledgeList] = useState<Knowledge[]>([]);
  // 文章总条数
  const [knowledgeTotal, setKnowledgeTotal] = useState<number>(0);

  /**
   * @description 获取文章分页列表的回调函数
   * */
  const fetchKnowledge = async () => {
    try {
      setLoading(true);
      const { rows, total } = await enhanceDispatch(fetchKnowledgeList(knowledgeParams)).unwrap();
      const newknowledgeList = [...knowledgeList, ...rows];
      setknowledgeList(newknowledgeList);
      setKnowledgeTotal(total);
      setKnowledgeParams((prevState) => ({ ...prevState, current: prevState.current += 1 }));
      if (newknowledgeList.length >= total) setHasMore(false);
    } catch (rejectedValueOrSerializedError: any) {
      Toast.show(rejectedValueOrSerializedError);
    } finally {
      setLoading(false);
    }
  };


  /**
   * @description 渲染文章item的回调函数
   *
   const renderKnowledgeCard = () => {
   if (loading) {
   return (<div className="lazyLoading"><SpinLoading color="primary" /></div>);
   } else {
   return (
   knowledgeList.map(item => {
   return <KnowledgeCard key={item.id} knowledge={item}></KnowledgeCard>;
   })
   );
   }
   };
   */

  return (
    <div className="knowledge-list">
      {
        knowledgeList.map(item => <KnowledgeCard key={item.id} knowledge={item}></KnowledgeCard>)
      }
      <InfiniteScroll loadMore={fetchKnowledge} hasMore={hasMore}></InfiniteScroll>
    </div>
  );
};

export default KnowledgeList;